package com.ruoyi.cms.controller.admin;

import com.ruoyi.cms.common.BaseController;
import com.ruoyi.cms.domain.Archives;
import com.ruoyi.cms.service.ArchivesService;
import com.ruoyi.cms.service.LabelService;
import com.ruoyi.common.core.domain.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/cms/label")
public class LabelController extends BaseController {
    @Autowired
    private LabelService labelService;
    @Autowired
    private ArchivesService archivesService;

    @GetMapping("/getLabelMap")
    public R<Map<String, List<Map<String,String>>>> getLabel() {
        Map<String, List<Map<String,String>>> map = labelService.queryLabel();
        return R.ok(map);
    }

    @GetMapping("/getLabelClass")
    public R<String[]> getLabelClass() {
        String[] classs = {"label-default","label-primary","label-success","label-info","label-inverse","label-warning","label-danger"};
        return R.ok(classs);
    }

    @RequestMapping("/delete")
    public int delete(String tagName) {
        List<Archives> list = archivesService.queryListByTagName(tagName);
        if(list != null && list.size()>0) {
            for(int i=0;i<list.size();i++) {
                StringBuffer sb = new StringBuffer();
                Archives article = list.get(i);
                String tag = article.getTag();
                String[] tags = tag == null ? null : tag.split(",");
                if(tags != null && tags.length > 0) {
                    for(int j = 0;j < tags.length;j++) {
                        String temp = tags[j];
                        if(!tagName.equals(temp)) {
                            sb.append(temp + ",");
                        }
                    }
                    String newTag = sb.length() > 0 ? sb.substring(0, sb.length() - 1) : "";
                    article.setTag(newTag);
                    archivesService.updateTagById(article);
                }
            }
        }
        return labelService.deleteByTagName(tagName);
    }
}
